﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using AdventureWorks.DAL.Setup;
using AdventureWorks.Model.Entities;

namespace AdventureWorks.DAL.DAO
{
	public class CustomerRepository : IGenericRepository<Customer>
	{
		private readonly IDbSet<Customer> _db;
		private readonly DbContext _context;

		public CustomerRepository()
		{
			_context = new AdventureWorksContext();
			_db = _context.Set<Customer>();
		}

		public CustomerRepository(DbContext context,IDbSet<Customer> db)
		{
			_context = context;
			_db = db;
		}

		public void Delete(int id)
		{
			var c = _db.FirstOrDefault(i => i.CustomerID == id);
			Delete(c);
		}

		public void Delete(Customer entityToDelete)
		{
			_db.Remove(entityToDelete);
		}

		public IEnumerable<Customer> Get(Expression<Func<Customer, bool>> filter = null, Func<IQueryable<Customer>, IOrderedQueryable<Customer>> orderBy = null, string includeProperties = "")
		{
			IQueryable<Customer> query = _db;

			if (filter != null)
				query = query.Where(filter);

			foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
			{
				query = query.Include(includeProperty);
			}

			return orderBy != null ? orderBy(query).ToList() : query.ToList();
		}

		public IEnumerable<Customer> Get()
		{
			return _db.ToList();
		}

		public Customer Get(int id)
		{
			return _db.FirstOrDefault(i => i.CustomerID == id);
		}

		public void Insert(Customer entity)
		{
			_db.Add(entity);
		}

		public void Update(Customer entityToUpdate)
		{
			_db.Attach(entityToUpdate);
			_context.Entry(entityToUpdate).State = EntityState.Modified;
		}

		public void Dispose()
		{
			throw new NotImplementedException();
		}
	}
}
